//https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/?envType=daily-question&envId=2024-02-21



/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* _buildTree(vector<int>& postorder, vector<int>& inorder, int& prei, int inbegin, int inend)
    {
        if(inbegin > inend) return nullptr;
        TreeNode* node = new TreeNode(postorder[prei]);
        int inoi = inend;
        while(inoi >= inbegin)
        {
            if(inorder[inoi] == postorder[prei])
            {
                break;
            }
            else
                --inoi;
        }
        --prei;
        node->right = _buildTree(postorder, inorder, prei,inoi + 1, inend);

        node->left = _buildTree(postorder, inorder, prei, inbegin, inoi - 1);
        return node;
    }

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int i = postorder.size() - 1;
        return _buildTree(postorder, inorder, i, 0, inorder.size() - 1);

    }
};


